/**
 *
 */
package com.sense.kukoo.common.file

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.File
import java.lang.Exception
import java.math.BigDecimal

// 图片保存路径
const val IMAGE_PATH = "images"

// 音频保存路径
const val VOICE_PATH = "voices"

// 视频保存路径
const val VIDEO_PATH = "videos"

// 更新安装包
const val UPDATE_APK_PATH = "apks"

//应用目录
const val SENSE_DIR = "sense"

object FileConfig {
    private val TAG = "FileConfig"
    private var voicesDir: String? = null
    private var imgDir: String? = null
    private var videoDir: String? = null
    private var apkDir: String? = null

    fun createDir(context: Context) {
        imgDir = getFileCacheDir(context, IMAGE_PATH)
        apkDir = getFileCacheDir(
            context,
            UPDATE_APK_PATH
        )
        voicesDir = getFileCacheDir(
            context,
            VOICE_PATH
        )
        videoDir = getFileCacheDir(
            context,
            VIDEO_PATH
        )
    }

    /**
     * @Description 创建app 私有文件目录
     * @Author Lionszhang
     * @Date 2021/11/15
     * @param dir 应用私用文件目录包名下第二级目录 path/dir
     * @return  文件夹路径
     */
    private fun getFileCacheDir(context: Context, dir: String): String {
        val appFileDir = File(context.getExternalFilesDir(SENSE_DIR), dir)
        if (!appFileDir.exists()) {
            appFileDir.mkdirs()
        }
        val path = appFileDir.absolutePath
        Log.e(TAG, "path=$path")
        return path
    }

    fun getVoiceDir(): String? {
        return voicesDir
    }

    fun getVideoDir(): String? {
        return videoDir
    }

    fun getApkDir(): String? {
        return apkDir
    }

    fun getImgDir(): String? {
        return imgDir
    }


    /**
     * 获取当前缓存
     *
     * @param context
     * @return
     * @throws Exception
     */
    @Throws(Exception::class)
    fun getTotalCacheSize(context: Context): String {
        var cacheSize = getFolderSize(context.cacheDir)
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            cacheSize += getFolderSize(context.externalCacheDir)
        }
        return getFormatSize(cacheSize.toDouble())
    }

    /**
     * 清空缓存
     *
     * @param context
     */
    fun clearAllCache(context: Context) {
        deleteDir(context.cacheDir)
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            deleteDir(context.externalCacheDir)
        }
    }

    private fun deleteDir(dir: File?): Boolean {
        if (dir != null && dir.isDirectory) {
            val children = dir.list()
            for (i in children.indices) {
                val success = deleteDir(File(dir, children[i]))
                if (!success) {
                    return false
                }
            }
        }
        return dir!!.delete()
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    @Throws(Exception::class)
    fun getFolderSize(file: File?): Long {
        var size: Long = 0
        try {
            val fileList = file!!.listFiles()
            for (i in fileList.indices) {
                // 如果下面还有文件
                size = if (fileList[i].isDirectory) {
                    size + getFolderSize(fileList[i])
                } else {
                    size + fileList[i].length()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return size
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    fun getFormatSize(size: Double): String {
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            return size.toString() + "Byte"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(java.lang.Double.toString(kiloByte))
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(java.lang.Double.toString(megaByte))
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(java.lang.Double.toString(gigaByte))
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                .toPlainString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return (result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB")
    }

}